package com.pri.chat.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.entity.LocalMedia;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.DTBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.R;
import com.pri.chat.activity.DTmsgActivity;
import com.pri.chat.activity.NetPicShowActivity;
import com.pri.chat.activity.OtherPeopleMsgActivity;
import com.pri.chat.activity.PeopleMsgActivity;
import com.pri.chat.activity.ReleaseJuBaoAcctivity;
import com.pri.chat.activity.ShareMemberActivity;
import com.pri.chat.adapter.DTAdapter;
import com.pri.chat.dialog.DialogUtil;
import com.pri.chat.event.EventTag;
import com.pri.chat.event.MessageEvent;
import com.pri.chat.model.DTModel;
import com.pri.chat.model.SayModel;
import com.pri.chat.model.ZanModel;
import com.pri.chat.utils.Des3Util;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.fragment.FragmentLazy;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author wx5e48d604c2885118
 * @time 2020/4/7
 */
public class MemberDTFragment extends FragmentLazy implements BaseQuickAdapter.OnItemChildClickListener ,BaseQuickAdapter.OnItemClickListener{
    @BindView(R.id.rec_main)
    RecyclerView recMain;
    @BindView(R.id.none)
    ImageView none;
    @BindView(R.id.srl_all)
    SmartRefreshLayout srlAll;
    private String mOtherName;
    private String mOtherId ;

    public static MemberDTFragment getInstance(String mOtherId, String mOtherName) {
        MemberDTFragment fragment = new MemberDTFragment();
        fragment.mOtherId = mOtherId;
        fragment.mOtherName = mOtherName;
        return fragment;
    }

    Unbinder unbinder;

    @Override
    protected View initViews(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstanceState) {
        View view = layoutInflater.inflate(R.layout.fragment_dt_layout, viewGroup, false);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        init();
        initSrl();

        return view;
    }

    public void updateDaCall(String memberId, int sfdc){
        //type 0--打招呼；1--修改其他信息
        for(int i=0;i<mList.size();i++){
            if(mList.get(i).getMemberId().equals(memberId)){
                mList.get(i).setSfdc(sfdc);
                mAdapter.notifyItemChanged(i);
            }
        }
    }

    public void updateDongTai(DTBean obj){
        //type 0--打招呼；1--修改其他信息
        for(int i=0;i<mList.size();i++){
            if(mList.get(i).getId().equals(obj.getId())){
                mAdapter.setData(i,obj);
                break;
            }
        }
    }

    public void deleteDongTai(DTBean obj){
        //type 0--打招呼；1--修改其他信息
        for(int i=0;i<mList.size();i++){
            if(mList.get(i).getId().equals(obj.getId())){
                mList.remove(i);
                mAdapter.notifyDataSetChanged();
                break;
            }
        }
    }

    private Dialog mShareDialog;
    private void initShareDialog(String path,int pos) {
        String memberId = SharedHelper.readId(mContext);
        String listMemberId = mList.get(pos).getMemberId();
        int type = 1;
        if(listMemberId.equals(memberId)){
            type = 2;
        }
        mShareDialog= DialogUtil.getInstance().showShareDialog(mContext,type);
        DialogUtil.getInstance().setOnShareClickListener(new DialogUtil.OnShareClickListener() {
            @Override
            public void qqOnClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("id",mList.get(pos).getId());
                bundle.putString("image",path);
                bundle.putString("title",mList.get(pos).getMemberName());
                bundle.putString("content",mList.get(pos).getContent());
                bundle.putInt("type",0);
                RxActivityTool.skipActivity(mContext, ShareMemberActivity.class,bundle);
                mShareDialog.dismiss();
            }

            @Override
            public void circleOnClick(View v) {
                mShareDialog.dismiss();
                DialogUtil.getInstance().shareWechatMoments(path,HttpMethods.SHARE_TITLE,mList.get(pos).getContent(),HttpMethods.SHARE_URL);
            }

            @Override
            public void qZoneOnClick(View v) {
                mShareDialog.dismiss();
                //删除操作
                deleteDongTai(pos);
            }

            @Override
            public void weixinOnClick(View v) {
                mShareDialog.dismiss();
                DialogUtil.getInstance().shareWeChat(path,HttpMethods.SHARE_TITLE,mList.get(pos).getContent(),HttpMethods.SHARE_URL);
            }
            @Override
            public void jubaoOnClick(View v) {
                mShareDialog.dismiss();
                Bundle bundle = new Bundle();
                bundle.putString("id",mList.get(pos).getId());
                bundle.putString("type","0");
                RxActivityTool.skipActivity(mContext, ReleaseJuBaoAcctivity.class,bundle);
            }
        });
        mShareDialog.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshData(MessageEvent messageEvent) {
        if(messageEvent.getTag().equals(EventTag.DT)){
            refresh();
        }

    }



    public void refresh() {
        isShowDialog = false;
        page = 1;
        mList.clear();
        mAdapter.notifyDataSetChanged();
        initData();
    }

    public void updateDongTai(DTBean obj,int position){
        if(obj.getSfdc() != mList.get(position).getSfdc()){
            for(int i=0;i<mList.size();i++){
                if(mList.get(i).getMemberId().equals(obj.getMemberId())){
                    mList.get(i).setSfdc(obj.getSfdc());
                    mAdapter.notifyItemChanged(i);
                }
            }
        }else if(obj.getPlNum().equals(mList.get(position).getPlNum())){
            mAdapter.setData(position,obj);
        }else if(obj.getSfdz() != mList.get(position).getSfdz()){
            mAdapter.setData(position,obj);
        }
    }

    private void initSrl() {
        srlAll.setOnRefreshListener(refresh_layout -> {
            refresh_layout.finishRefresh(1000);
            refresh();
        });
        srlAll.setOnLoadmoreListener(refresh_layout -> {
            refresh_layout.finishLoadmore(1000);
            isShowDialog = false;
            page++;
            initData();
        });
    }
    private List<DTBean> mList;
    private DTAdapter mAdapter;
    private void init() {
        mList=new ArrayList<>();
        ((SimpleItemAnimator)recMain.getItemAnimator()).setSupportsChangeAnimations(false);
        LinearLayoutManager linearLayoutManager =new LinearLayoutManager(mContext);
        recMain.setLayoutManager(linearLayoutManager);
        mAdapter=new DTAdapter(R.layout.item_dt,mList);
        recMain.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.setOnImageClickListener(new DTAdapter.OnImageClickListener() {
            @Override
            public void onItemClick(View view, int c_pos, int f_pos) {
//                PictureSelector.create(mContext)
//                        .themeStyle(R.style.picture_default_style)
//                        .isNotPreviewDownload(true)
//                        .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
//                        .openExternalPreview(c_pos, mList.get(f_pos).getMediaList());
                Bundle bundle = new Bundle();
                bundle.putInt("item",c_pos);
                bundle.putSerializable("listPath",(Serializable) mList.get(f_pos).getImgs());
                RxActivityTool.skipActivity(mContext, NetPicShowActivity.class,bundle);
            }
        });

    }
    private int page=1;
    private boolean isShowDialog=true;
    @Override
    protected void initData() {
        SubscriberOnNextListener<BaseBean<List<DTBean>>> onNextListener = baseBean -> {
            if(baseBean.getData().isEmpty()&&page==1){
                none.setVisibility(View.VISIBLE);
                mAdapter.notifyDataSetChanged();
                srlAll.setEnableLoadmore(false);
            }else {
                none.setVisibility(View.INVISIBLE);
                mList.addAll(baseBean.getData());
                for(int i=0;i<mList.size();i++){
                    String imgs[]=mList.get(i).getPicList().split(",");
                    List<String> list =new ArrayList<>();
                    List<LocalMedia> mediaList =new ArrayList<>();
                    for(int j=0;j<imgs.length;j++){
                        LocalMedia localMedia=new LocalMedia();
                        list.add(imgs[j]);
                        localMedia.setPath(imgs[j]);
                        mediaList.add(localMedia);

                    }
                    mList.get(i).setImgs(list);
                    mList.get(i).setMediaList(mediaList);
                }
                mAdapter.notifyDataSetChanged();
                if(baseBean.getData().size()<10){
                    srlAll.setEnableLoadmore(false);
                }
            }
        };
        String lat = SharedHelper.readValueByKeyForString(mContext,"lat");
        String lng = SharedHelper.readValueByKeyForString(mContext,"lng");
        DTModel dtModel = new DTModel(page,0, SharedHelper.readId(mContext),lat,lng,null,null);//登录上传参数
        dtModel.setSendMemberId(mOtherId);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(dtModel));
        HttpMethods.getInstance().dt_list(new ProgressSubscriber<>(onNextListener, mContext, isShowDialog), requestBody);
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()){
            case R.id.zanLinear:
                httpLike(position);
                break;
            case R.id.iv_logo:
                if(mList.get(position).getMemberId().equals(SharedHelper.readId(mContext))){
                    RxActivityTool.skipActivity(mContext, PeopleMsgActivity.class);
                }else{
                    Bundle bundle =new Bundle();
                    bundle.putString("id",mList.get(position).getMemberId());
                    RxActivityTool.skipActivity(mContext, OtherPeopleMsgActivity.class,bundle);
                }
                break;
            case R.id.tv_say_hello:
                if(mList.get(position).getSfdc() == 1){
                    return;
                }
                if(SharedHelper.readId(mContext).equals(mList.get(position).getMemberId())){
                    RxToast.normal("不能给自己打招呼");
                }else {
                    httpSayHello(position);
                }
                break;
            case R.id.iv_share:
                if(!mList.get(position).getImgs().get(0).isEmpty()){
                    initShareDialog(mList.get(position).getImgs().get(0),position);
                }else {
                    initShareDialog("",position);
                }

                break;
        }
    }
    private void httpSayHello(int position) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal("打招呼成功");
            for(int i=0;i<mList.size();i++){
                if(mList.get(i).getMemberId().equals(mList.get(position).getMemberId())){
                    mList.get(i).setSfdc(1);
                    mAdapter.notifyItemChanged(i);
                }
            }
            RxToast.normal(baseBean.getMsg());
        };
        SayModel userModel = new SayModel();
        userModel.setMemberId(SharedHelper.readId(mContext));
        userModel.setOtherMemberId(mList.get(position).getMemberId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(userModel));
        HttpMethods.getInstance().callMember(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }
    private static final String TAG = "DTFragment";
    private void httpLike(int pos) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            Log.d(TAG, "onNext: " + baseBean.toString());
            if(mList.get(pos).getSfdz()==0){
                mList.get(pos).setSfdz(1);
                mList.get(pos).setZanNum(mList.get(pos).getZanNum()+1);
            }else {
                mList.get(pos).setSfdz(0);
                mList.get(pos).setZanNum(mList.get(pos).getZanNum()-1);
            }
            mAdapter.notifyItemChanged(pos);
            RxToast.normal(baseBean.getMsg());
        };
        ZanModel zanModel = new ZanModel();
        zanModel.setBdzId(mList.get(pos).getId());
        zanModel.setDzrId(SharedHelper.readId(mContext));
        zanModel.setType(0);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(zanModel));
        HttpMethods.getInstance().saveDianZan(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        unbinder.unbind();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        Intent intent =new Intent(mContext, DTmsgActivity.class);
        Bundle bundle_2 = new Bundle();
        bundle_2.putParcelable("dt", mList.get(position));
        bundle_2.putInt("position", position);
        intent.putExtras(bundle_2);
        mContext.startActivity(intent);
    }

    private void deleteDongTai(int position) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            if(baseBean.isSuccess()){
                RxToast.normal("删除成功！");
                mList.remove(position);
                mAdapter.notifyDataSetChanged();
            }
        };

        Map<String,Object> params = new HashMap<>();
        params.put("id",mList.get(position).getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().deleteDongTai(new ProgressSubscriber<>(onNextListener, mContext, isShowDialog), requestBody);
    }
}
